﻿namespace Nintest.ConsoleRunner
{
    using System;
    using System.IO;
    using System.Reflection;

    using Nintest.Model;

    internal static class Program
    {
        internal static void Main(string[] args)
        {
            if (args.Length < 1)
                ShowHelp();

            var fileInfo = new FileInfo(args[0]);
            if (!fileInfo.Exists)
                Console.Error.WriteLine("Could not find file: " + fileInfo.FullName);

            var assemblyname = new AssemblyName { CodeBase = fileInfo.FullName };
            var testAssembly = Assembly.Load(assemblyname);

            var runner = new TestRunner(testAssembly);
            runner.Trace += OnTrace;
            runner.Run();
        }

        private static void ShowHelp()
        {
            Console.Error.WriteLine(@"Usage: {0} <TestAssembly.dll>", typeof(Program).Assembly.CodeBase);
        }

        private static void OnTrace(object sender, TraceEventArgs e)
        {
            var writer = e.Level < TraceLevel.Error ? Console.Out : Console.Error;
            var localTime = e.UtcTime.ToLocalTime();
            var level = GetLevelString(e.Level);
            writer.WriteLine("{0:O} {1} {2}", localTime, level, e.Message);
        }

        private static string GetLevelString(TraceLevel level)
        {
            switch (level)
            {
                case TraceLevel.Trace:
                    return "TRC";
                case TraceLevel.Debug:
                    return "DBG";
                case TraceLevel.Info:
                    return "INF";
                case TraceLevel.Error:
                    return "ERR";
                case TraceLevel.Fatal:
                    return "FTL";
                default:
                    return "???";
            }
        }
    }
}
